package cn.edu.zafu.bigdata.hdb;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TimeServer {
    public static void main(String[] args) {
        int port = 12345; // 服务端端口号
        try (DatagramSocket socket = new DatagramSocket(port)) {
            System.out.println("时钟同步服务端已启动，等待请求...");

            while (true) {
                byte[] buffer = new byte[1024];
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

                // 接收客户端请求
                socket.receive(packet);
                String request = new String(packet.getData(), 0, packet.getLength());
                System.out.println("收到请求: " + request);

                // 获取当前时间
                String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

                // 准备回复数据
                byte[] responseData = currentTime.getBytes();
                DatagramPacket responsePacket = new DatagramPacket(responseData, responseData.length,
                        packet.getAddress(), packet.getPort());

                // 发送当前时间给客户端
                socket.send(responsePacket);
                System.out.println("发送当前时间: " + currentTime);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
